<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
    //个人页面设置
	public function setting()
	{
		$me = \Auth::user();
        return view('user/setting', compact('me'));
	}
	//个人页面设置储存
	public function settingStore(Request $request)
	{
		$this->validate(request(),[
            'name' => 'min:3',
        ]);
        $name = request('name');
        $user = \Auth::user();
        if ($name != $user->name) {
            if(\App\User::where('name', $name)->count() > 0) {
                return back()->withErrors(array('message' => '用户名称已经被注册'));
            }
            $user->name = request('name');
        }
        if ($request->file('avatar')) {
            $path = $request->file('avatar')->storePublicly(md5(\Auth::id() . time()));
            $user->avatar = "/storage/". $path;
        }
        $user->save();
        return back();
	}
	//个人中心页面
	public function show(User $user)
	{
		// 用户的信息,包含 关注/粉丝/文章数
		$user = User::withCount(['stars','fans','posts'])->find($user->id);
		//文章列表，前10条
		$posts = $user->posts()->orderBy('created_at','desc')->take(3)->get();
		//关注的用户 包含 关注/粉丝/文章数
		$stars = $user->stars;

		$susers = User::whereIn('id',$stars->pluck('star_id'))->withcount(['stars','fans','posts'])->get();

		//粉丝数 包含 关注/粉丝/文章数
		$fans = $user->fans;
		$fusers = User::whereIn('id',$fans->pluck('fan_id'))->withcount(['stars','fans','posts'])->get();
		return view('user/show',compact('user','posts','susers','fusers'));
	}
	//关注用户
	public function fan(User $user)
	{
		$me = \Auth::user();
		$me->doFan($user->id);
		return [
			'errcode'=>0,
			'errmsg'=>'success'
		];
	}
	//取关用户
	public function unfan(User $user)
	{
		$me = \Auth::user();
		$me->doUnfan($user->id);
		return [
			'errcode'=>0,
			'errmsg'=>'success'
		];
	}
}
